//
//  RecordModel.swift
//  Md5Compare
//
//  Created by mx004 on 17/11/24.
//  Copyright © 2017年 mx004. All rights reserved.
//

import Foundation



class RecordModel:NSObject,NSCoding {
    
    static let shared:RecordModel = GetRecordModel();
    
    var dir1:String = ""
    var dir2:String = ""
    
    override init() {
        super.init();
    }
    

    
    required init?(coder aDecoder: NSCoder) {
        super.init()
        dir1 = aDecoder.decodeObject(forKey: "dir1") as! String
        dir2 = aDecoder.decodeObject(forKey: "dir2") as! String

    }
    
    func encode(with aCoder: NSCoder) {
        aCoder.encode(dir1, forKey: "dir1")
        aCoder.encode(dir2, forKey: "dir2")
    }
    
    
    /**
     创建文件夹 如果存在则不创建
     - parameter filePath: 文件路径
     return 是否有文件夹存在
     */
    func CreatFilePath(_ filePath:String) ->Bool {
        let fileManager = FileManager.default
        // 文件夹是否存在
        if fileManager.fileExists(atPath: filePath) {
            return true
        }
        do{
            try fileManager.createDirectory(atPath: filePath, withIntermediateDirectories: true, attributes: nil)
            return true
        }catch{}
        return false
    }
    
    /// 归档阅读文件文件
    func WriteKanModel(object:AnyObject) {
        //var path = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!) + "/\(folderName)"
        var path =  NSTemporaryDirectory() + "/tmp"
        if (CreatFilePath(path)) { // 创建文件夹成功或者文件夹存在
            path = path + "/md5_record.txt"
            NSKeyedArchiver.archiveRootObject(object, toFile: path)
        }
    }
    
    /// 解档阅读文件文件
    class func ReadKanModel() ->AnyObject? {
        //let path = ((NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as String) + "/\(folderName)") + "/\(fileName)"
        let path =  NSTemporaryDirectory() + "/tmp/md5_record.txt"
        return NSKeyedUnarchiver.unarchiveObject(withFile: path) as AnyObject?
    }
    
    func save(dir1:String,dir2:String) {
        self.dir1 = dir1
        self.dir2 = dir2
        WriteKanModel( object: self)
    }
    
    class func GetRecordModel() -> RecordModel {
        var model:RecordModel!
        
        let path =  NSTemporaryDirectory() + "/tmp/md5_record.txt"
        print("path:\(path)")
        if FileManager.default.fileExists(atPath: path) {
            model = ReadKanModel() as! RecordModel
        }
        
        if model == nil {
            model = RecordModel();
        }
        
        return model!
    }
    

}
